package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.ICategoryService;
import com.itheima.reggie.service.IDishFlavorService;
import com.itheima.reggie.service.IDishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private IDishService dishService;
    @Autowired
    private IDishFlavorService dishFlavorService;
    @Autowired
    private ICategoryService categoryService;
    /**
     * 新增菜品分类
     * @param dishDto
     * @return
     */
    @PostMapping
    public R save(@RequestBody DishDto dishDto){
        //保存菜品数据 到dish表
        dishService.save(dishDto);
        //保存口味数据 到dishflavor表
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            //设置口味对应的菜品id
            flavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(flavors);
        return R.success(null);
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(Integer page,Integer pageSize,String name){
        //创建page对象，设置当前页和每页大小
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        // 封装查询条件 where name like '%%'
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        //封装排序
        qw.orderByDesc(Dish::getUpdateTime);
        //开始查询
        dishService.page(pageInfo,qw);
        //总条数
        long total = pageInfo.getTotal();
        //查询列表数据
        List<Dish> records = pageInfo.getRecords();
        Map map = new HashMap<>();
        map.put("total",total);
        // records: List<Dish>
        // 只有菜品分类id：categoryId，没有分类名称
        // 根据菜品分类id，查询菜品分类数据。在set进去
        // List<Dish> records ---> List<DishDto> dishDtos
        // for循环的写法：
//        List<DishDto> dishDtos = new ArrayList<>();
//        for (Dish dish : records) {
//            //获取菜品分类id
//            Long categoryId = dish.getCategoryId();
//            Category category = categoryService.getById(categoryId);
//            //获取到了当前分类的名称
//            String categoryName = category.getName();
//            // 新建一个DishDto 将分类名称set进入
//            DishDto dishDto = new DishDto();
//            dishDto.setCategoryName(categoryName);
//            // 还需要将Dish dish 数据放入到 DishDto dishDto 里面
//            BeanUtils.copyProperties(dish,dishDto);
//            dishDtos.add(dishDto);
//        }
        // 拉姆达表达式的写法： List<Dish> records ---> List<DishDto> dishDtos
        List<DishDto> dishDtos1 = records.stream().map((dish) -> {
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            DishDto dishDto = new DishDto();
            dishDto.setCategoryName(categoryName);
            BeanUtils.copyProperties(dish, dishDto);
            return dishDto;
        }).collect(Collectors.toList());
        map.put("records",dishDtos1);
        return R.success(map);
    }

    /**
     * 根据id查询菜品数据，用于回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R get(@PathVariable Long id){
        //1、查询菜品数据 select * from dish where id = ?
        Dish dish = dishService.getById(id);
        //2、查询菜品对应的口味数据 select * from dish_flavor where dish_id = ?
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> list = dishFlavorService.list(qw);
        //返回DishDto对象，先new出该对象 DishDto dishDto = new DishDto();
        DishDto dishDto = new DishDto();
        // 把dish菜品数据 赋值/拷贝 给 dishDto对象 BeanUtils.copyProperties
        BeanUtils.copyProperties(dish,dishDto);
        // 设置dishDto的口味数据 dishDto.setFlavors(xxx)
        dishDto.setFlavors(list);
        // 返回数据 ;
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R update(@RequestBody DishDto dishDto){
        // 1、修改菜品dish表的数据
        dishService.updateById(dishDto);
        //取出菜品id Long dishId = dishDto.getId();
        Long dishId = dishDto.getId();
        // 2、修改菜品的口味数据 如何完成？？
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId,dishId);
        // 2.1 先删除原有的口味数据: delete from dish_flavor where dish_id = ?
        dishFlavorService.remove(qw);
        // 2.2 添加菜品口味数据 List<DishFlavor> flavors = dishDto.getFlavors();
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishId);
        }
        dishFlavorService.saveBatch(flavors);
        return R.success("修改成功");
    }

    /**
     * 删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public R delete(@RequestParam List<Long> ids){
        for (Long id : ids) {
            Long categoryId = dishService.getById(id).getCategoryId();
            if (categoryService.getById(categoryId).getType()!=1){
                return R.error("删除失败");
            }
        }
        dishService.removeByIds(ids);
        return R.success("删除成功");
    }

    /**
     * 起售 停售
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R updateStatus(@PathVariable Integer status, @RequestParam List<Long> ids){
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            dish.setStatus(status);
            dishService.updateById(dish);
        }
        return R.success("操作成功");
    }

    /**
     * 根据条件查询对应的菜品数据
     * @param
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Long categoryId ,Integer status){
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(Dish::getCategoryId,categoryId);
        //添加条件
        qw.eq(Dish::getStatus,1);
        //添加排序条件
        qw.orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(qw);
        List<DishDto> dishDtos = new ArrayList<>();
        for (Dish dish : list) {
            DishDto dishDto = new DishDto();
            //菜品的数据
            BeanUtils.copyProperties(dish,dishDto);
            //口味的数据
            LambdaQueryWrapper<DishFlavor> qw1 = new LambdaQueryWrapper<>();
            qw1.eq(DishFlavor::getDishId,dish.getId());
            List<DishFlavor> list1 = dishFlavorService.list(qw1);
            dishDto.setFlavors(list1);
            dishDtos.add(dishDto);
        }
        return R.success(dishDtos);
    }
}
